922D - Robot Vacuum Cleaner - CodeForces Solution


greedy sortings *1800

Please click on ads to support us..

Python Code:

import heapq
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

n = int(input())
h = []
inf = pow(10, 9) + 1
ans = 0
for _ in range(n):
    t = list(input().rstrip())
    c = [0] * 2
    x = 0
    for i in t:
        c[i & 1] += 1
        if not i & 1:
            ans += c[1]
    if not c[0]:
        heapq.heappush(h, (0, c[1], c[0]))
    elif not c[1]:
        heapq.heappush(h, (inf, c[1], c[0]))
    else:
        heapq.heappush(h, (c[0] / c[1], c[1], c[0]))
c = 0
while h:
    _, u, v = heapq.heappop(h)
    ans += c * v
    c += u
print(ans)

C++ Code:

#include<bits/stdc++.h>
using namespace std;
const long long maxn=1e5+5;
long long n,ans,sans,s[maxn],h[maxn],value[maxn],id[maxn];
char a[maxn];
bool cmp(long long ida,long long idb);
long long cost(long long a,long long b);
int main(){
	scanf("%lld",&n);
	for(long long i=1;i<=n;i++){
		scanf("%s",(a+1));
		for(long long j=1,len=strlen(a+1);j<=len;j++){
			if(a[j]=='s')s[i]++;
			else value[i]+=s[i],h[i]++;
		}
		id[i]=i;
	}
	sort(id+1,id+1+n,cmp);
	for(long long i=1;i<=n;i++){
		ans+=value[id[i]]+sans*h[id[i]];
		sans+=s[id[i]];
	}
	printf("%lld",ans);
	return 0;
}
bool cmp(long long ida,long long idb){
	return cost(ida,idb)>cost(idb,ida);
}
long long cost(long long a,long long b){
	return value[a]+value[b]+s[a]*h[b];
}


Comments

Submit
0 Comments
More Questions

230A - Dragons
200B - Drinks
13A - Numbers
129A - Cookies
1367B - Even Array
136A - Presents
1450A - Avoid Trygub
327A - Flipping Game
411A - Password Check
1520C - Not Adjacent Matrix
1538B - Friends and Candies
580A - Kefa and First Steps
1038B - Non-Coprime Partition
43A - Football
50A - Domino piling
479A - Expression
1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns